// pages/Visitor/index.js
const QR = require("../../utils/qrcode.js");


const utils = require('../../utils/activity_util')
import WeCropper from '../../components/we-cropper/we-cropper.js'
const device = wx.getSystemInfoSync()
const width = 375
const height = 503


let app = getApp();
const HttpAjax = getApp().getHttpData;
import Dialog from '../../components/dist/dialog/dialog';
import Toast from '../../components/dist/toast/toast';


// 初始化日期模态框数据
let date = new Date();
let years = [];
let months = [];
let days = [];
let hours = [];
let minutes = [];

for (let i = date.getFullYear(); i <= (date.getFullYear() + 5); i++) {
  years.push(i + "年")
}
for (let i = 1; i <= 12; i++) {
  months.push(i + "月")
}
for (let i = 1; i <= 31; i++) {
  days.push(i + "日")
}
for (let i = 0; i <= 23; i++) {
  hours.push(i + "")
}
for (let i = 0; i <= 59; i++) {
  minutes.push(i + "")
}

// const nowtime = utils.getDate(years, months, days, hours, minutes)

Page({

  /**
   * 页面的初始数据
   */
  data: {
    ishaspep: false,//没账套
    loadendtxt: '当前没绑定账套,去添加账套',
    VisitorName: "1233",//姓名
    Reason: "公事",//事由
    Remark: "",//备注
    Phone: "13929757412",//手机号
    VisitorCardNo: "",//证件号
    AccessID: 1,//权限组ID
    Expiry: utils.getobjDate(),//有效期
    Interviewee: "",//被访人
    Address: "",//访问地址

    changefalg: false,
    value: [0, 1, 1, 1, 1],
    openflag: true,  //1日期控件显示  2控件滚动选择 底部页面不滚动
    years: years,   //时间可选范围模态框数据
    months: months,
    days: days,
    hours: hours,
    minutes: minutes,
    year: '',  //时间值
    month: '',
    day: '',
    hour: '',
    minute: '',
    starttime: utils.getobjDate(),


    // Data: [{ AccessID: 1, GroupName: "123", PermitTime: "2019-09-29 09:31:18", TimePiece: 1, ReadCount: 65535 }, { AccessID: 2, GroupName: "1234", PermitTime: "2019-09-29 09:31:18", TimePiece: 1, ReadCount: 65535 }],
    Data:[],
    Index:0,
    imagePath:'',
    base64Image:'',
    qrCode_show:false,
    returncardnum:'',
    image: '../../image/write.png',
    cropperOpt: {
      id: 'cropper',
      targetId: 'targetCropper',
      pixelRatio: device.pixelRatio,
      width,
      height,
      scale: 2.5,
      zoom: 8,
      cut: {
        x: (width - 320) / 2,
        y: (height - 440) / 2,
        width: 320,
        height: 440
      },
      boundStyle: {
        color: '#04b00f',
        mask: 'rgba(0,0,0,0.8)',
        lineWidth: 1
      }
    },
    cWidth: 0,
    cHeight: 0,
    show:false,
    imageChange:false,

    isshowtz:false,

    Reasonindex:0,
    ReasonArr:['公事','快递','私事','外卖','其它']
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    
    let that = this;
    this.setData({
      ishaspep: false,//没账套
      isshowtz: false,
      loadendtxt: '当前没绑定账套,去添加账套',
    })

    this.GetCustomerList();

    
    const {
      cropperOpt
    } = that.data
    cropperOpt.boundStyle.color = '#04b00f'
    that.setData({
      cropperOpt
    })
    console.log(that.data.image)
    if (that.data.image) {
      cropperOpt.src = that.data.image
      that.cropper = new WeCropper(cropperOpt)
        .on('ready', (ctx) => {
          // console.log(`wecropper is ready for work!`)
        })
        .on('beforeImageLoad', (ctx) => {
          // console.log(`before picture loaded, i can do something`)
          // console.log(`current canvas context:`, ctx)
        })
        .on('imageLoad', (ctx) => {
          // console.log(`picture loaded`)
          // console.log(`current canvas context:`, ctx)
          wx.hideToast()
        })
        .on('beforeDraw', (ctx, instance) => {
          // console.log(`before canvas draw,i can do something`)
          // console.log(`current canvas context:`, ctx)
        })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  /**
   * 获取套账
   */
  GetCustomerList(){
    let that=this;
    wx.showToast({
      title: '数据加载中',
      icon: 'loading',
      duration: 2000,
      mask:true
    })
    HttpAjax(app.globalData.url + '/Door/GetCustomerList', {}, 'post', app.globalData.headerCookie).then(res=>{
      let rest = res.data;
      
      wx.hideToast()
      if (rest.result == 1) {
        
        if (rest.customerlist.length >= 1) {
          that.setData({
            ishaspep: true,
            isshowtz: true,
            Interviewee: rest.customerlist[0].PName
          })
          HttpAjax(app.globalData.url + '/Visitor/GetAccessGroup', {}, 'post', app.globalData.headerCookie).then(res => {
            that.setData({
              Data: res.data
            })
            that.data.AccessID = res.data[0].AccessID;
          })
        }else{
          that.setData({
            ishaspep: false,
            isshowtz: true
          })
        }
      }
    }).catch(err=>{
      wx.hideToast()
      that.setData({
        ishaspep: false,
        isshowtz: true
      })
    })


  },

  /**
   * 跳到添加账套页
   */
  toaddcurm() {
    wx.navigateTo({
      url: '../bindCard/addcard/index',
    })
  },

  OnChange(e) {
    // console.log(e.currentTarget.dataset.name);
    let json = {};
    json[e.currentTarget.dataset.name] = e.detail;
    // console.log(json)
    this.setData(json)
  },
  tap(ev) {

    // 根据选择项目  传去对应数据  根据开始结束时间获取索引  设置面板默认数据

    let value = [2019, 0, 0, 0, 0];
    let arr = [];
    arr = utils.getarrWithtime(this.data.starttime);

    const { years, months, days, hours, minutes, openflag } = this.data;
    //根据arr  数据索引
    value[0] = years.indexOf(arr[0] + '年');
    value[1] = months.indexOf(arr[1] + '月');
    value[2] = days.indexOf(arr[2] + '日');
    value[3] = hours.indexOf(arr[3]);
    value[4] = minutes.indexOf(arr[4]);

    this.setData({
      value,
      openflag: false,
      years,   //日期模态框数据
      months,
      days,
      hours,
      minutes,
    })

  },
  // 取消
  canslebtn() {

    this.setData({
      openflag: true,
      changefalg: false,
    })
  },
  // 确定  如果不选择那么默认重置
  closebtn() {

    this.setData({
      openflag: true,
    })
    const { curindex, year, month, day, hour, minute } = this.data;
    // console.log(this.data.changefalg)
    if (this.data.changefalg) {
      let starttime = utils.getDate(year, month, day, hour, minute)
      // console.log('starttime', starttime)
      this.setData({
        starttime,
        Expiry: starttime,
        changefalg: false,
      })
    }else{
      let starttime = utils.getDate(year, month, day, hour, minute)
      this.setData({
        Expiry: starttime,
      })
    }
  },

  bindChange: function (ev) {

    const e = ev;
    let val = e.detail.value;

    const year = this.data.years[val[0]];
    const month = this.data.months[val[1]];
    const day = this.data.days[val[2]];
    const hour = this.data.hours[val[3]];
    const minute = this.data.minutes[val[4]];

    //如果点击月份  那么后面日跟着变换数据
    let days = [];
    const daynum = utils.mGetDate(year.substr(0, year.length - 1), month.substr(0, month.length - 1));
    for (let i = 1; i <= daynum; i++) {
      days.push(i + "日")
    }

    this.setData({
      days,
      year,
      month,
      day,
      hour,
      minute,
      changefalg: true,
    })
  },
  upload() {
    console.log(13213);
    // this.cropper.pushOrign(this.data.image)
    this.setData({
      show: true
    });
    console.log(this.data.image)
    this.cropper.pushOrign(this.data.image)
  },
  cancel() {
    this.setData({
      show: false
    });
  },
  touchStart(e) {
    this.cropper.touchStart(e)
  },
  touchMove(e) {
    this.cropper.touchMove(e)
  },
  touchEnd(e) {
    this.cropper.touchEnd(e)
  },
  getCropperImage() {
    console.log('上传照片')
    let that=this;
    this.cropper.getCropperImage({
      quality: .1,
    }, (path, err) => {
      console.log(path, err)
      if (err) {
        wx.showModal({
          title: '温馨提示',
          content: err.message
        })
      } else {
        that.setData({
          image: path,
          show: false,
          imageChange:true
        })
        

      }
    })
  },
  uploadTap() {
    const self = this

    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success(res) {
        const src = res.tempFilePaths[0]
        //  获取裁剪图片资源后，给data添加src属性及其值

        self.cropper.pushOrign(src)
      }
    })
  },
  
  
  cutImage(imgsrc) {
    console.log(imgsrc)
    let that = this;
    let p = new Promise((resolve, reject) => {
      wx.getImageInfo({
        src: imgsrc,
        success: function (res) {
          //---------利用canvas压缩图片--------------
          var ratio = 1;
          console.log(res)
          var canvasWidth = res.width //图片原始长宽
          var canvasHeight = res.height
          while (canvasWidth > 400 || canvasHeight > 440) { // 保证宽高在400以内
            canvasWidth = 320
            canvasHeight = 440
            ratio++;
          }
          that.setData({
            cWidth: canvasWidth,
            cHeight: canvasHeight
          })

          //----------绘制图形并取出图片路径--------------
          var ctx = wx.createCanvasContext('canvas')
          ctx.drawImage(res.path, 0, 0, canvasWidth, canvasHeight)
          ctx.draw(false, setTimeout(function () {
            wx.canvasToTempFilePath({
              canvasId: 'canvas',
              destWidth: 320,
              destHeight: 440,
              success: function (res) {
                console.log(res.tempFilePath) //最终图片路径
                resolve(res)
              },
              fail: function (res) {
                console.log(res.errMsg)
                reject(res)
              }
            })
          }, 100))
        },
        fail: function (res) {
          reject(res)
          console.log(res.errMsg)
        }
      })
    })
    return p;
  },

  AddPeo(){
    console.log('开始提交')
    if (this.data.VisitorName===''){
      Toast('请输入访客姓名')
      setTimeout(()=>{
        Toast.clear()
      },1500)
      return
    }
    // console.log(this.data.Phone != '', this.data.VisitorCardNo != '', !(this.data.Phone != '' || this.data.VisitorCardNo != ''))
    if (!(this.data.Phone != '' || this.data.VisitorCardNo != '')) {
      Toast('请输入手机号或者证件号');
      setTimeout(() => {
        Toast.clear()
      }, 1500)
      return
    }
    let d;
    if (this.data.Phone !== ''){
      if (d = /^[1][3,4,5,7,8][0-9]{9}$/, !1 === d.test(this.data.Phone)) return void Toast('请输入正确的手机号');
    }
    if (this.data.VisitorCardNo !== '') {
      if (d = /^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$|^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/, !1 === d.test(this.data.VisitorCardNo)) return void Toast('请输入正确的证件号');
    }
    if (this.data.Interviewee === '') {
      Toast('请输入被访公司或人员')
      return
    }

    let that=this;
    
    // console.log(this.data.image)
    
    let parma = {
      VisitorName: this.data.VisitorName,//姓名
      Reason: this.data.Reason,//事由
      Remark: this.data.Remark,//备注
      Phone: this.data.Phone,//手机号
      VisitorCardNo: this.data.VisitorCardNo,//证件号
      AccessID: this.data.AccessID,//权限组ID
      Expiry: this.data.Expiry,//有效期
      Interviewee: this.data.Interviewee,//被访人
      Address: this.data.Address,//访问地址
      base64: "" //访客照片(可选)
    }
    if(this.data.AccessID){
      HttpAjax(app.globalData.url + '/Visitor/GetDoorValidType', {AccessID:this.data.AccessID}, 'post', app.globalData.headerCookie).then(res => {
        if (this.data.imageChange) {
      
      
          this.cutImage(that.data.image).then(res => {
            console.log(res)
            wx.getFileSystemManager().readFile({
              filePath: res.tempFilePath, //选择图片返回的相对路径
              encoding: 'base64', //编码格式
              success: res => {
                console.log(res)
                let base64Url = wx.arrayBufferToBase64(res.data);
                let imgdata = 'data:image/' + 'JPG' + ';base64,' + res.data;
                parma.base64 = imgdata;
                HttpAjax(app.globalData.url + '/Visitor/AddVisitor', parma, 'post', app.globalData.headerCookie).then(res => {
                  console.log('123456------------')
                  if (res.data.result) {
                    that.formSubmit(res.data.CardData)
                    that.setData({
                      returncardnum: res.data.CardData,
                      image: '../../image/write.png',
                      imageChange:false
                    })
                  } else {
                    Toast(res.data)
                    setTimeout(() => {
                      Toast.clear()
                    }, 1500)
                  }
    
                }).catch(err => {
                  console.error(err)
                })
              },
              fail: res => {
                console.log(res)
              }
            })
          }).catch(err => {
            console.log(err)
          })
        }else{
          HttpAjax(app.globalData.url + '/Visitor/AddVisitor', parma, 'post', app.globalData.headerCookie).then(res => {
            // console.log(res)
            return res
          }).then(res => {
            console.log('456789------------')
    
            if (res.data.result) {
              that.formSubmit(res.data.CardData)
              that.setData({
                image: '../../image/write.png',
                returncardnum: res.data.CardData
              })
            } else {
              Toast(res.data)
              setTimeout(() => {
                Toast.clear()
              }, 1500)
            }
    
          }).catch(err => {
            console.error(err)
          })
        }
            
      })
    }else{
      HttpAjax(app.globalData.url + '/Visitor/AddVisitor', parma, 'post', app.globalData.headerCookie).then(res => {
        // console.log(res)
        return res
      }).then(res => {
        console.log('456789------------')

        if (res.data.result) {
          that.formSubmit(res.data.CardData)
          that.setData({
            image: '../../image/write.png',
            returncardnum: res.data.CardData
          })
        } else {
          Toast(res.data)
          setTimeout(() => {
            Toast.clear()
          }, 1500)
        }

      }).catch(err => {
        console.error(err)
      })
    }
    
    
    

    
  },
  toVisitorList(){
    wx.navigateTo({
      url: './VisitorList/index',
    })
  },
  pickerBindChange(e){
    console.log(e, this.data.Data[e.detail.value].AccessID);
    let AccessID = this.data.Data[e.detail.value].AccessID;
    let parma={AccessID:AccessID}
    HttpAjax(app.globalData.url + '/Visitor/GetDoorValidType', parma, 'post', app.globalData.headerCookie).then(res=>{
      console.log(res)
    })
    this.setData({
      Index:e.detail.value,
      AccessID: AccessID
    })

  },
  ReasonBindChange(e){
    console.log(e.detail.value)
    let that=this;
    let idx = e.detail.value
    this.setData({
      Reasonindex: idx,
      Reason: that.data.ReasonArr[idx]
    })
  },
  close(){
    this.setData({
      qrCode_show: false
    })
  },













  //适配不同屏幕大小的canvas
  setCanvasSize: function () {
    var size = {};
    try {
      var res = wx.getSystemInfoSync();
      var scale = 750 / 686;//不同屏幕下canvas的适配比例；设计稿是750宽
      var width = res.windowWidth / scale;
      var height = width;//canvas画布为正方形
      size.w = width;
      size.h = height;
    } catch (e) {
      // Do something when catch error
      console.log("获取设备信息失败" + e);
    }
    return size;
  },
  createQrCode: function (url, canvasId, cavW, cavH) {
    //调用插件中的draw方法，绘制二维码图片
    QR.api.draw(url, canvasId, cavW, cavH);
    setTimeout(() => {
      this.canvasToTempImage(); 
      this.setData({
        qrCode_show: true
      });}, 500);

  },
  //获取临时缓存照片路径，存入data中
  canvasToTempImage: function () {
    var that = this;
    wx.canvasToTempFilePath({
      canvasId: 'mycanvas',
      success: function (res) {
        var tempFilePath = res.tempFilePath;
        console.log(tempFilePath);
        // that.setData({
        //   imagePath: tempFilePath,
        //   // canvasHidden:true
        // });




        // 生成二维码信息

        that.canvasCustom(tempFilePath, that.data.returncardnum).then(res=>{
          setTimeout(()=>{
            wx.canvasToTempFilePath({
              canvasId: 'shareCanvas',
              success: function (res) {
                var tempFilePath = res.tempFilePath;
                // console.log(tempFilePath);
                that.setData({
                  imagePath: tempFilePath,
                  // maskHidden: false
                  // canvasHidden:true
                });
              },
              fail: function (res) {
                console.log(res);
              }
            });
          },500)
        })







      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  //点击图片进行预览，长按保存分享图片
  previewImg: function (e) {
    var img = this.data.imagePath;
    console.log(img);
    wx.previewImage({
      current: img, // 当前显示图片的http链接
      urls: [img] // 需要预览的图片http链接列表
    })
  },
  formSubmit: function (e) {
    var that = this;
    var url = e;
    that.setData({
      qrCode_show: false,
      imagePath:''
    });
    wx.showToast({
      title: '生成访客二维码...',
      icon: 'loading',
      duration: 3000
    });
    var st = setTimeout(function () {
      wx.hideToast()
      var size = that.setCanvasSize();
      //绘制二维码
      that.createQrCode(url, "mycanvas", size.w, size.h);
      
      clearTimeout(st);
    }, 500)

  },
  canvasCustom(path,num){
    let that = this;
    var size = that.setCanvasSize();
    // debugger;
    let canvaswidths = size.w;
    let qrwidth = size.w;//二维码宽度
    const ctx = wx.createCanvasContext('shareCanvas');
    // ctx.drawImage(res.path, 0, 60, that.data.canvasWidth, 400)
    ctx.clearRect(0, 0, canvaswidths, canvaswidths * 1.4);
    ctx.fillStyle = "#fff";
    ctx.fillRect(0, 0, canvaswidths, canvaswidths * 1.4);
    ctx.drawImage(path, (canvaswidths - qrwidth) / 2, 0, qrwidth, qrwidth) //二维码
    // console.log(app.userInfo.avatarUrl)
    // ctx.drawImage( (canvaswidths - 50) / 2, 60 + (canvaswidths - 50) / 2, 50, 50) //头像
    ctx.setTextAlign('center') // 文字居中
    ctx.setFillStyle('#000000') // 文字颜色：黑色
    ctx.setFontSize(18) // 文字字号：22px
    ctx.fillText('二维码有效期：' + that.data.Expiry, canvaswidths / 2, canvaswidths -10)
    ctx.fillText('卡号：' + num, canvaswidths / 2, canvaswidths-30)

    ctx.fillText('访客二维码', canvaswidths / 2, 30)
    ctx.stroke()
    ctx.draw()
    return new Promise((res,rej)=>{
      res(123)
    })
  }
})